<?php


namespace App\Models\CacheModel;


use App\Models\Api\BaseCache;
use Exception;
use think\Config;
use think\exception\DbException;
use think\Log;
use AstroTool\Cache\CacheManage;

/**
 * 用户钱包明细
 * Class ZhunleUserAccountRecord
 * @package App\Models\CacheModel
 */
class ZhunleUserAccountRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zhunle_user_account_record';
    protected $cacheModel = 'user.coin_detail';

    /**
     * 添加用户准币明细
     * @param int $uid
     * @param array $data
     * @return bool|int|string
     * @throws Exception
     */
    public function SaveData($uid, $data)
    {
        try
        {
            $id = $this->insertGetId($data);
        }
        catch (\Exception $e)
        {
            Log::write($uid . '添加用户准币明细失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】');
            return false;
        }
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache('list');
        return (int)$id;
    }

    /**
     * 更新用户钱包明细数据
     * @param int $uid
     * @param int $id
     * @param array $data
     * @param array $where
     * @return bool
     * @throws Exception
     */
    public function UpdateData($uid, $id, $data, $where)
    {
        try
        {
            $this->where($where)->update($data);
        }
        catch (\Exception $e)
        {
            Log::write($uid . '更新用户准币明细失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】');
            return false;
        }
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache('list');
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();
        return true;
    }

    /**
     * 缓存获取用户准币明细
     * @param int $uid
     * @param bool $isPaging
     * @return array|mixed
     * @throws Exception
     */
    public function getUserCoinDetailListFromCache($uid, $isPaging = true)
    {
        $page = input('page', 1);
        $limit = $this->pageLimit ?: Config::get('paginate.list_rows');

        if (!$isPaging)
        {
            $page = -1; // 获取所有数据
        }

        $sortKey = 'id';

        $data = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage($page)
            ->setPageSize($limit)
            ->setSort('desc')
            ->getListPage(function ($ids = [], $isCache = true, $sortType = 'desc') use ($uid)
            {
                if ($isCache)
                { // 开启了缓存
                    return $this->getInfoByIdsInData($ids, [$uid], $sortType);
                } else
                { // 没开启缓存
                    return $this->getPaginateInData([$uid], $sortType);
                }
            }, $sortKey, [], 0, 'list', 'list_details');

        if (!$isPaging)
        {
            return $data['data'];
        }

        return $data;
    }

    /**
     * 分页获取用户准币明细
     * @param array $type
     * @param string $sortType
     * @return array|void
     * @throws DbException
     */
    public function getPaginateInData($type, $sortType)
    {
        $where = ['uid' => $type[0], 'status' => 1];
        $data = $this
            ->where($where)
            ->order("id {$sortType}")
            ->field('id,uid,consumer_type,order_type,gid,pray_date,total_amount,coin_num,balance,order_id,trade_type,create_time,update_time,extend')->paginate()->toArray();
        return $data;
    }

    /**
     * 数据库批量获取用户准币明细
     * @param array $ids
     * @param array $type
     * @param string $sortType
     * @return array|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $field = 'id,uid,consumer_type,order_type,gid,pray_date,total_amount,coin_num,balance,order_id,trade_type,create_time,update_time,extend';
        if ($ids)
        {
            $where = ['id' => ['in', $ids], 'status' => 1];
        } else
        {
            $where = ['uid' => $type[0], 'status' => 1];
        }
        try
        {
            $data = $this->where($where)->order('id', 'DESC')->column($field, 'id');
        }
        catch (Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    /**
     * 获取用户今天许愿信息
     * @param int $uid
     * @param int $rid
     * @param string $time 日期 格式为 20191212
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function getTodayPrayInfo(int $uid, int $rid, $time = null)
    {
        $time = $time ?? date('Ymd');

        $key = $uid . ':' . $rid . ':' . $time;
        $data = CacheManage::getInstance()->setCacheConfig('fortune.pray_day', $key)->getDataAndSet(function () use ($uid, $rid, $time)
        {
            try
            {
                $gids = $this->where(['status' => 1, 'uid' => $uid, 'rid' => $rid, 'pray_date' => $time])->column('gid');
                $data = [];
                foreach ($gids as $value)
                {
                    $data[$value] = $value;
                }
            }
            catch (Exception $e)
            {
                Log::write('获取用户许愿信息错误' . $e->getMessage(), 'error');
                $data = [];
            }
            // 如果为空 则写入一个空值 防止缓存穿透
            return $data ?: [''];
        });
        // 过滤空值
        return array_filter($data);
    }

    /**
     * 添加许愿记录
     * @param int $uid 用户ID
     * @param int $rid 档案ID
     * @param null $time 许愿日期 【20191230】
     * @param array $prayData [10000=>10000] 许愿ID
     * @throws Exception
     */
    public function prayAdd(int $uid, int $rid, $time = null, $prayData = [])
    {
        $time = $time ?? date('Ymd');

        $key = $uid . ':' . $rid . ':' . $time;

        CacheManage::getInstance()->setCacheConfig('fortune.pray_day', $key)->setCache($prayData);
    }
}
